<template>
  <div class="project-tsa-wrapper">
    <div class="flex justify-center">
      <h2 class="text-white title">{{ username }}</h2>
    </div>
    <div class="scrollbar" :style="{ height: scorllHeight + 'px' }">
      <a-collapse :bordered="false" expandIconPosition="right" accordion style="background: #232323">
        <a-collapse-panel :key="EDeviceTypeName.Dock" header="机场" style="border-bottom: 1px solid #4f4f4f">
          <div v-if="onlineDocks.data.length === 0" style="height: 150px; color: white" class="flex justify-center">
            <a-empty :image="noData" :image-style="{ height: '100px' }" />
          </div>
          <div v-else class="fz12" style="color: white">
            <div v-for="dock in onlineDocks.data" :key="dock.sn" class="item-derect">
              <div class="flex justify-between px-2 items-center h-9 text-base" style="border: 1px solid #595959">
                <a-tooltip :title="`${dock.gateway.callsign} - ${dock.callsign ?? 'No Drone'}`">
                  <div class="text-hidden" style="max-width: 200px">
                    {{ dock.gateway.callsign }} - {{ dock.callsign ?? 'No Drone' }}
                  </div>
                </a-tooltip>
                <div class="border-l pl-1 border-[#303030]">
                  <div
                    class="fz16 cursor-pointer flex items-center py-1"
                    @click="
                      switchVisible(
                        $event,
                        dock,
                        true,
                        dockInfo[dock.gateway.sn] && dockInfo[dock.gateway.sn].basic_osd?.mode_code !== EDockModeCode.Disconnected
                      )
                    "
                  >
                    <EyeOutlined v-if="osdVisible.gateway_sn === dock.gateway.sn && osdVisible.visible" />
                    <EyeInvisibleOutlined v-else />
                  </div>
                </div>
              </div>
              <div>
                <div class="mt5 flex" style="border: 1px solid #595959">
                  <div class="flex-align-center flex-row flex-1" @click="goToDock(dock)">
                    <span class="ml5 mr5"><RobotOutlined /></span>
                    <div
                      class="font-bold text-hidden cursor-pointer"
                      style="max-width: 100px"
                      :style="
                        dockInfo[dock.gateway.sn] && dockInfo[dock.gateway.sn].basic_osd?.mode_code !== EDockModeCode.Disconnected
                          ? 'color: #00ee8b'
                          : 'color: red;'
                      "
                    >
                      {{
                        dockInfo[dock.gateway.sn]
                          ? EDockModeCodeStatus[dockInfo[dock.gateway.sn].basic_osd?.mode_code]
                          : EDockModeCodeStatus[EDockModeCode.Disconnected]
                      }}
                    </div>
                  </div>
                  <div class="flex justify-center items-center" style="">
                    <div v-if="hmsInfo[dock.gateway.sn]" class="flex-align-center flex-row">
                      <div
                        :class="
                          hmsInfo[dock.gateway.sn][0].level === EHmsLevel.CAUTION
                            ? 'caution-blink'
                            : hmsInfo[dock.gateway.sn][0].level === EHmsLevel.WARN
                            ? 'warn-blink'
                            : 'notice-blink'
                        "
                        style="width: 18px; text-align: center"
                      >
                        <span :style="hmsInfo[dock.gateway.sn].length > 99 ? 'font-size: 11px' : 'font-size: 12px'">{{
                          hmsInfo[dock.gateway.sn].length
                        }}</span>
                        <span class="fz10">{{ hmsInfo[dock.gateway.sn].length > 99 ? '+' : '' }}</span>
                      </div>
                      <a-popover
                        trigger="click"
                        placement="bottom"
                        color="black"
                        v-model:visible="hmsVisible[dock.gateway.sn]"
                        @visibleChange="readHms(hmsVisible[dock.gateway.sn], dock.gateway.sn)"
                        :overlayStyle="{ width: '200px', height: '300px' }"
                      >
                        <div
                          :class="
                            hmsInfo[dock.gateway.sn][0].level === EHmsLevel.CAUTION
                              ? 'caution'
                              : hmsInfo[dock.gateway.sn][0].level === EHmsLevel.WARN
                              ? 'warn'
                              : 'notice'
                          "
                          class="w-32"
                        >
                          <span class="word-loop">{{ hmsInfo[dock.gateway.sn][0].message_zh }}</span>
                        </div>
                        <template #content>
                          <a-collapse
                            style="background: black; height: 300px; overflow-y: auto"
                            :bordered="false"
                            expand-icon-position="right"
                            :accordion="true"
                          >
                            <a-collapse-panel
                              v-for="hms in hmsInfo[dock.gateway.sn]"
                              :key="hms.hms_id"
                              :showArrow="false"
                              style="margin: 0 auto 3px auto; border: 0; width: 140px; border-radius: 3px"
                              :class="
                                hms.level === EHmsLevel.CAUTION ? 'caution' : hms.level === EHmsLevel.WARN ? 'warn' : 'notice'
                              "
                            >
                              <template #header="{ isActive }">
                                <div class="flex-row flex-align-center" style="width: 130px">
                                  <div style="width: 110px">
                                    <span class="word-loop">{{ hms.message_zh }}</span>
                                  </div>
                                  <div
                                    style="width: 20px; height: 15px; font-size: 10px; z-index: 2"
                                    class="flex-row flex-align-center flex-justify-center"
                                    :class="
                                      hms.level === EHmsLevel.CAUTION
                                        ? 'caution'
                                        : hms.level === EHmsLevel.WARN
                                        ? 'warn'
                                        : 'notice'
                                    "
                                  >
                                    <DoubleRightOutlined :rotate="isActive ? 90 : 0" />
                                  </div>
                                </div>
                              </template>

                              <a-tooltip :title="hms.create_time">
                                <div style="color: white" class="text-hidden">{{ hms.create_time }}</div>
                              </a-tooltip>
                            </a-collapse-panel>
                          </a-collapse>
                        </template>
                      </a-popover>
                    </div>
                    <div v-else class="width-100" style="height: 90%; background: rgba(0, 0, 0, 0.35)"></div>
                  </div>
                </div>
                <div class="mt5 flex" style="border: 1px solid #595959">
                  <div class="flex flex-1 items-center">
                    <span class="ml5 mr5"><RocketOutlined /></span>
                    <div
                      class="font-bold text-hidden cursor-pointer"
                      @click="handleGoTo(dock)"
                      style="max-width: 100px"
                      :style="
                        deviceInfo[dock.sn] && deviceInfo[dock.sn].mode_code !== EModeCode.Disconnected
                          ? 'color: #00ee8b'
                          : 'color: red;'
                      "
                    >
                      {{
                        deviceInfo[dock.sn]
                          ? EModeCodeStatus[deviceInfo[dock.sn].mode_code]
                          : EModeCodeStatus[EModeCode.Disconnected]
                      }}
                    </div>
                    <div
                      title="第一视角"
                      v-if="deviceInfo[dock.sn]"
                      class="ml-auto mr-2 cursor-pointer"
                      :style="{ backgroundColor: dock.sky ? '#00ee8b' : '#ff0000' }"
                      @click="handleSky(dock)"
                    >
                      <img width="16" height="16" :src="FirstViewIcon" alt="" />
                    </div>
                  </div>
                  <div class="flex justify-center items-center flex-1">
                    <div v-if="hmsInfo[dock.sn]" class="flex">
                      <div
                        :class="
                          hmsInfo[dock.sn][0].level === EHmsLevel.CAUTION
                            ? 'caution-blink'
                            : hmsInfo[dock.sn][0].level === EHmsLevel.WARN
                            ? 'warn-blink'
                            : 'notice-blink'
                        "
                        style="width: 18px; text-align: center"
                      >
                        <span :style="hmsInfo[dock.sn].length > 99 ? 'font-size: 11px' : 'font-size: 12px'">{{
                          hmsInfo[dock.sn].length
                        }}</span>
                        <span class="fz10">{{ hmsInfo[dock.sn].length > 99 ? '+' : '' }}</span>
                      </div>
                      <a-popover
                        trigger="click"
                        placement="bottom"
                        color="black"
                        v-model:visible="hmsVisible[dock.sn]"
                        @visibleChange="readHms(hmsVisible[dock.sn], dock.sn)"
                        :overlayStyle="{ width: '200px', height: '300px' }"
                      >
                        <div
                          :class="
                            hmsInfo[dock.sn][0].level === EHmsLevel.CAUTION
                              ? 'caution'
                              : hmsInfo[dock.sn][0].level === EHmsLevel.WARN
                              ? 'warn'
                              : 'notice'
                          "
                          style="max-width: 130px"
                        >
                          <span class="word-loop">{{ hmsInfo[dock.sn][0].message_zh }}</span>
                        </div>
                        <template #content>
                          <a-collapse
                            style="background: black; height: 300px; overflow-y: auto"
                            :bordered="false"
                            expand-icon-position="right"
                            :accordion="true"
                          >
                            <a-collapse-panel
                              v-for="hms in hmsInfo[dock.sn]"
                              :key="hms.hms_id"
                              :showArrow="false"
                              style="margin: 0 auto 3px auto; border: 0; width: 140px; border-radius: 3px"
                              :class="
                                hms.level === EHmsLevel.CAUTION ? 'caution' : hms.level === EHmsLevel.WARN ? 'warn' : 'notice'
                              "
                            >
                              <template #header="{ isActive }">
                                <div class="flex-row flex-align-center" style="width: 130px">
                                  <div style="width: 110px">
                                    <span class="word-loop">{{ hms.message_en }}</span>
                                  </div>
                                  <div
                                    style="width: 20px; height: 15px; font-size: 10px; z-index: 2"
                                    class="flex-row flex-align-center flex-justify-center"
                                    :class="
                                      hms.level === EHmsLevel.CAUTION
                                        ? 'caution'
                                        : hms.level === EHmsLevel.WARN
                                        ? 'warn'
                                        : 'notice'
                                    "
                                  >
                                    <DoubleRightOutlined :rotate="isActive ? 90 : 0" />
                                  </div>
                                </div>
                              </template>

                              <a-tooltip :title="hms.create_time">
                                <div style="color: white" class="text-hidden">{{ hms.create_time }}</div>
                              </a-tooltip>
                            </a-collapse-panel>
                          </a-collapse>
                        </template>
                      </a-popover>
                    </div>
                    <div v-else class="width-100" style="height: 90%; background: rgba(0, 0, 0, 0.35)"></div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </a-collapse-panel>
      </a-collapse>
      <a-collapse :bordered="false" expandIconPosition="right" accordion style="background: #232323">
        <a-collapse-panel :key="EDeviceTypeName.Aircraft" header="在线设备" style="border-bottom: 1px solid #4f4f4f">
          <div v-if="onlineDevices.data.length === 0" style="height: 150px; color: white" class="flex justify-center">
            <a-empty :image="noData" :image-style="{ height: '100px' }" />
          </div>

          <div v-else class="fz12" style="color: white">
            <div v-for="device in onlineDevices.data" :key="device.sn" class="pb-2 item-derect">
              <div class="battery-slide" v-if="deviceInfo[device.sn]">
                <div style="background: #535759; width: 100%"></div>
                <div class="capacity-percent" :style="{ width: deviceInfo[device.sn].battery.capacity_percent + '%' }"></div>
                <div class="return-home" :style="{ width: deviceInfo[device.sn].battery.return_home_power + '%' }"></div>
                <div class="landing" :style="{ width: deviceInfo[device.sn].battery.landing_power + '%' }"></div>
                <div class="battery" :style="{ left: deviceInfo[device.sn].battery.capacity_percent + '%' }"></div>
              </div>
              <div class="uav-derect">
                <div class="uav-header flex justify-between items-center">
                  <span class="text-hidden border-r border-gray-300 flex-1 mr-1">{{
                    device.model ? `${device.model} - ${device.callsign}` : 'No Drone'
                  }}</span>
                  <div
                    class="fz16 flex items-center cursor-pointer"
                    @click="
                      switchVisible(
                        $event,
                        device,
                        false,
                        deviceInfo[device.sn] && deviceInfo[device.sn].mode_code !== EModeCode.Disconnected
                      )
                    "
                  >
                    <EyeOutlined v-if="osdVisible.sn === device.sn && osdVisible.visible" />
                    <EyeInvisibleOutlined v-else />
                  </div>
                </div>
                <div class="flex flex-col gap-1.5 px-1.5 pt-1">
                  <div class="uav-common flex gap-2 items-center">
                    <span class="">
                      <img src="@/assets/icons/uav.svg" alt="svg" />
                    </span>
                    <span
                      class="font-bold"
                      :style="
                        deviceInfo[device.sn] && deviceInfo[device.sn].mode_code !== EModeCode.Disconnected
                          ? 'color: #00ee8b'
                          : 'color: red;'
                      "
                    >
                      {{
                        deviceInfo[device.sn]
                          ? EModeCodeStatus[deviceInfo[device.sn].mode_code]
                          : EModeCodeStatus[EModeCode.Disconnected]
                      }}
                    </span>
                  </div>
                  <div class="uav-common flex items-center gap-1">
                    <span class=""><img src="@/assets/icons/rc.svg" alt="" /></span>
                    <a-tooltip>
                      <template #title>{{ device.gateway.model }} - {{ device.gateway.callsign }} </template>
                      <div class="text-hidden text-white">{{ device.gateway.model }} - {{ device.gateway.callsign }}</div>
                    </a-tooltip>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </a-collapse-panel>
      </a-collapse>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { computed, onMounted, reactive, ref, watch, WritableComputedRef } from 'vue'
import * as Cesium from 'cesium'
import { EDeviceTypeName, ELocalStorageKey } from '@/types'
import noData from '@/assets/icons/no-data.png'
import rc from '@/assets/icons/rc.png'
import {
  OnlineDevice,
  EModeCode,
  OSDVisible,
  EDockModeCode,
  DeviceOsd,
  EDockModeCodeStatus,
  EModeCodeStatus
} from '@/types/device'
import { useMyStore } from '@/store'
import { getDeviceTopo, getUnreadDeviceHms, updateDeviceHms } from '@/api/manage'
import { RocketOutlined, EyeInvisibleOutlined, EyeOutlined, RobotOutlined, DoubleRightOutlined } from '@ant-design/icons-vue'
import { EHmsLevel } from '@/types/enums'
import useGMapManage from '@/hooks/use-g-map'
import { getLonLatByCartesian } from '@/utils/cesium.utils'
import { sessionStorage } from '@/utils/storage'
import FirstViewIcon from '@/assets/icons/sky.svg'
import deviceTsaUpdateHook from '@/hooks/use-model'

const store = useMyStore()
const username = ref(sessionStorage.get(ELocalStorageKey.Username))
const workspaceId = ref(sessionStorage.get(ELocalStorageKey.WorkspaceId)!)
const osdVisible = computed(() => store.state.osdVisible)
const hmsVisible = new Map<string, boolean>()
const scorllHeight = ref()

const onlineDevices = reactive({
  data: [] as OnlineDevice[]
})

const onlineDocks = reactive({
  data: [] as OnlineDevice[]
})

const deviceInfo = computed(() => store.state.deviceState.deviceInfo)
const dockInfo = computed(() => store.state.deviceState.dockInfo)
const hmsInfo = computed({
  get: () => store.state.hmsInfo,
  set: (val) => {
    return val
  }
})

onMounted(() => {
  getOnlineTopo()
  setTimeout(() => {
    watch(
      () => store.state.deviceStatusEvent,
      (data) => {
        getOnlineTopo()
        if (data.deviceOnline.sn) {
          getUnreadHms(data.deviceOnline.sn)
        }
      },
      {
        deep: true
      }
    )
    getOnlineDeviceHms()
  }, 3000)
  const element = document.getElementsByClassName('scrollbar').item(0) as HTMLDivElement
  const parent = element?.parentNode as HTMLDivElement
  scorllHeight.value = parent?.clientHeight - parent?.firstElementChild?.clientHeight
})

const goToDock = (item: OnlineDevice) => {
  const viewer = useGMapManage.getViewer()
  const entity = viewer!.entities.getById(item.gateway.sn)! as Cesium.Entity
  console.log(entity, 'entity')
  if (!entity) {
    return
  }
  const { Lon, Lat } = getLonLatByCartesian(entity.position!.getValue(viewer.clock.currentTime)!)
  viewer.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(Lon, Lat, 600),
    duration: 5,
    orientation: {
      heading: Cesium.Math.toRadians(0),
      pitch: Cesium.Math.toRadians(-90),
      roll: 0
    }
  })
}
const handleGoTo = (item: OnlineDevice) => {
  const viewer = useGMapManage.getViewer()
  const entity = viewer!.entities.getById(item.gateway.sn)! as Cesium.Entity
  if (!entity) {
    return
  }
  const { Lon, Lat } = getLonLatByCartesian(entity.position!.getValue(viewer.clock.currentTime)!)
  viewer.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(Lon, Lat, 600),
    duration: 5,
    orientation: {
      heading: Cesium.Math.toRadians(0),
      pitch: Cesium.Math.toRadians(-90),
      roll: 0
    }
  })
}
const handleSky = (item: OnlineDevice) => {
  item.sky = !item.sky
  deviceTsaUpdateHook.adjustTheAngleOfView(item.sky, item.sn)
}

function getOnlineTopo() {
  getDeviceTopo(workspaceId.value).then((res) => {
    if (res.code !== 1) {
      return
    }
    onlineDevices.data = []
    onlineDocks.data = []
    res.data.forEach((gateway: any) => {
      const child = gateway.children
      const device: OnlineDevice = {
        model: child?.device_name,
        callsign: child?.nickname,
        sn: child?.device_sn,
        mode: EModeCode.Disconnected,
        gateway: {
          model: gateway?.device_name,
          callsign: gateway?.nickname,
          sn: gateway?.device_sn,
          domain: gateway?.domain
        },
        payload: [],
        sky: false
      }
      child?.payloads_list.forEach((payload: any) => {
        device.payload.push({
          index: payload.index,
          model: payload.model,
          payload_name: payload.payload_name,
          payload_sn: payload.payload_sn,
          control_source: payload.control_source,
          payload_index: payload.payload_index
        })
      })
      if (EDeviceTypeName.Dock === gateway.domain) {
        hmsVisible.set(device.sn, false)
        hmsVisible.set(device.gateway.sn, false)
        onlineDocks.data.push(device)
      }
      if (gateway.status && EDeviceTypeName.Gateway === gateway.domain) {
        onlineDevices.data.push(device)
      }
    })
  })
}

function switchVisible(e: any, device: OnlineDevice, isDock: boolean, isClick: boolean) {
  if (!isClick) {
    e.target.style.cursor = 'not-allowed'
    return
  }
  if (device.sn === osdVisible.value.sn) {
    osdVisible.value.visible = !osdVisible.value.visible
  } else {
    osdVisible.value.sn = device.sn
    osdVisible.value.callsign = device.callsign
    osdVisible.value.model = device.model
    osdVisible.value.visible = true
    osdVisible.value.gateway_sn = device.gateway.sn
    osdVisible.value.is_dock = isDock
    osdVisible.value.gateway_callsign = device.gateway.callsign
    osdVisible.value.payloads = device.payload
  }
  store.commit('SET_OSD_VISIBLE_INFO', osdVisible)
}

function getUnreadHms(sn: string) {
  getUnreadDeviceHms(workspaceId.value, sn).then((res) => {
    if (res.data.length !== 0) {
      hmsInfo.value[sn] = res.data
    }
  })
  console.info(hmsInfo.value)
}

function getOnlineDeviceHms() {
  const snList = Object.keys(dockInfo.value)
  console.log(snList, 'snList')
  if (snList.length === 0) {
    return
  }
  snList.forEach((sn) => {
    getUnreadHms(sn)
  })
  const deviceSnList = Object.keys(deviceInfo.value)
  if (deviceSnList.length === 0) {
    return
  }
  deviceSnList.forEach((sn) => {
    getUnreadHms(sn)
  })
}

function readHms(visiable: boolean, sn: string) {
  // if (!visiable) {
  //   updateDeviceHms(workspaceId.value, sn).then((res) => {
  //     if (res.code === 1) {
  //       delete hmsInfo.value[sn]
  //     }
  //   })
  // }
}

function openLivestreamOthers() {
  store.commit('SET_LIVESTREAM_OTHERS_VISIBLE', true)
}

function openLivestreamAgora() {
  store.commit('SET_LIVESTREAM_AGORA_VISIBLE', true)
}
</script>

<style lang="scss" scoped>
.project-tsa-wrapper > :first-child {
  height: 50px;
  line-height: 50px;
  align-items: center;
  border-bottom: 1px solid #4f4f4f;
}
.project-tsa-wrapper {
  height: 100%;
  .scrollbar {
    overflow: auto;
  }
  ::-webkit-scrollbar {
    display: none;
  }
}
:deep(.ant-collapse-header) {
  color: white !important;
  border: 0;
  padding-left: 14px;
}

.text-hidden {
  overflow: hidden !important;
  text-overflow: ellipsis !important;
  white-space: nowrap;
  -o-text-overflow: ellipsis;
}
.font-bold {
  font-weight: 700;
}

.battery-slide {
  width: 100%;
  .capacity-percent {
    background: #00ee8b;
  }
  .return-home {
    background: #ff9f0a;
  }
  .landing {
    background: #f5222d;
  }
  .battery {
    background: white;
    border-radius: 1px;
    width: 8px;
    height: 4px;
    margin-top: -3px;
  }
}
.battery-slide > div {
  position: relative;
  margin-top: -2px;
  min-height: 2px;
  border-radius: 2px;
  white-space: nowrap;
}
.disable {
  cursor: not-allowed;
}

.notice-blink {
  background: $success;
  animation: blink 500ms infinite;
}
.caution-blink {
  background: orange;
  animation: blink 500ms infinite;
}
.warn-blink {
  background: red;
  animation: blink 500ms infinite;
}
.notice {
  background: $success;
  overflow: hidden;
  cursor: pointer;
}
.caution {
  background: orange;
  cursor: pointer;
  overflow: hidden;
}
.warn {
  background: red;
  cursor: pointer;
  overflow: hidden;
}
.word-loop {
  white-space: nowrap;
  display: inline-block;
  animation: 10s loop linear infinite normal;
}
@keyframes blink {
  from {
    opacity: 1;
  }
  50% {
    opacity: 0.35;
  }
  to {
    opacity: 1;
  }
}
@keyframes loop {
  0% {
    transform: translateX(20px);
    -webkit-transform: translateX(20px);
  }
  100% {
    transform: translateX(-100%);
    -webkit-transform: translateX(-100%);
  }
}
.item-derect {
  background-color: rgba(219, 219, 219, 0.1);
}
.uav-derect {
  color: #fff;
  .uav-header {
    height: vh(36);
    background-color: rgba(219, 219, 219, 0.06);
    padding: 0px 4px 0px 4px;
    span {
      font-size: px2font(16);
    }
  }
  .uav-common {
    padding: 0px 4px 0px 4px;
    height: vh(25);
    background-color: rgba(48, 48, 48, 0.2);
    border: 1px solid rgb(112, 112, 112);
  }
}
.title {
  font-size: 28px;
}
</style>
